package com.abu.authms.service;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONUtil;
import com.abu.authms.client.UmsClient;
import com.abu.authms.config.CustomAuthException;
import com.abu.authms.properties.JwtProperties;
import com.abu.ums.pojo.Member;
import com.abu.utils.JwtUtils;
import com.abu.utils.R;
import me.zhyd.oauth.model.AuthResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.LinkedHashMap;

@Service
@EnableConfigurationProperties(JwtProperties.class)
public class AuthService {

    @Autowired
    private UmsClient umsClient;

    @Autowired
    private JwtProperties jwtProperties;

    public String getToken(String nickname, String password) {
//        通过用户名和密码获取用户
        Member member = this.umsClient.login(nickname, password);
//        将用户id和用户名放入map中
        return getToken(member);
    }

    public String checkLogin(AuthResponse authResponse) {
//        获取用户信息
        Object data = JSONUtil.toJsonStr(authResponse.getData());
        String dataJson = JSONUtil.toJsonStr(data);
        HashMap dataHashMap = JSONUtil.toBean(dataJson, HashMap.class);
//        获取nickname
        String nickname = (String) dataHashMap.get("nickname");
        String gender = (String) dataHashMap.get("gender");
//        获取token
        Object token = dataHashMap.get("token");
        String tokenStr = JSONUtil.toJsonStr(token);
        HashMap tokenHashMap = JSONUtil.toBean(tokenStr, HashMap.class);

//        获取用户openid
        String openId = (String) tokenHashMap.get("openId");
//        根据openid查询用户
        Member member = this.umsClient.getMember(openId);
//        如果不存在，添加用户
        if (member == null) {
            member = new Member();
            member
                    .setOpenid(openId)
                    .setSex(StringUtils.equals("女", gender) ? 1 : 2)
                    .setNickname(nickname);
            this.umsClient.saveMember(member);
        }
//       将用户信息放入HashMap中
        return getToken(member);
    }

    private String getToken(Member member) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("uid", member.getId());
        map.put("nickname", member.getNickname());
        String generateToken = null;
        try {
//            通过私钥加密
            generateToken = JwtUtils.generateToken(map, jwtProperties.getPrivateKey(), jwtProperties.getExpire() * 3);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return generateToken;
    }
}
